package com.kk.permission;

import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.kk.R;
import com.kk.permission.accessibilityutils.NodeUtil;
import com.kk.permission.adapter.PermissionStepAdapter;
import com.kk.permission.events.FinishEvent;
import com.kk.permission.events.ServiceInterruptEvent;
import com.kk.permission.handler.PermissionRouteHandler;
import com.kk.permission.progress.ProgressState;
import com.kk.permission.progress.ProgressUtil;
import com.kk.permission.utils.PackageUtil;
import com.kk.permission.utils.PrefUtil;
import com.kk.permission.utils.callershow.CallerShowUtils;
import com.kk.permission.utils.callershow.RxBus;
import com.kk.permission.view.PermissionStepFloatView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

public class PermissionStepActivity extends AppCompatActivity {

    private static final String TAG = "PermissionStepActivity";

    public static final int RESULT_SUCCESS = 66;
    public static final int RESULT_FAILED = 67;

    private RecyclerView mRecyclerView;
    private PermissionStepAdapter mPermissionStepAdapter;
    private Button mSetButton;
    private TextView mTitle;
    private AlertDialog mExitDialog;
    public static String AutoPopupWindowFlag = "AutoPopupWindowFlag";
    public static long endTime;
    public int KMaxRetryCount = 2;
    private Button btnState;
    private int currentPercent;
    private boolean isUseSetContentViewWaitProgress = false;
    private LinearLayout llContainer;
    private View mCommonView = null;
    private final int[] mCommonViewLoc = new int[2];
    //    public Context mContext = null;
    private HashMap<String, Integer> mExecuteMap = new HashMap();
    private boolean mFirstLoad = true;
    private Handler mHandler = new Handler();
    private boolean mIsOpenPopupWindow = true;
    private int mCurrentPermissionPos = 0;
    private boolean mPermissionEnterOnce;
    private int mLastPermissionPos;
    private boolean mUpdateFlag;
    private PermissionAccessibilityService.Listener mListener = new PermissionAccessibilityService.Listener() {
        public void onEvent(AccessibilityEvent accessibilityEvent) {
            if (mService != null && mStrategy != null) {
                if(!mPermissionEnterOnce) {
                    if(!PrefUtil.getBoolean(PermissionStepActivity.this, "AccessibilitySuccessStart")) {
                        PrefUtil.putBoolean(PermissionStepActivity.this,"AccessibilitySuccessStart", true);
                        PermissionWrapper.getInst().reportEvent("AccessibilitySuccessStart");
                    }
                    mPermissionEnterOnce = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(!mUpdateFlag &&  mService != null) {
                                NodeUtil.back(mService);
                                PermissionWrapper.getInst().reportEvent("ErrorPermission",
                                        Build.MODEL + "  " + Build.VERSION.RELEASE + "  "
                                                + ((mLastPermissionPos >= 0 && mLastPermissionPos < mPermissionList.size()) ? mPermissionList.get(mLastPermissionPos) : "Err: " + mLastPermissionPos));
                            }
                            mUpdateFlag = false;

                        }
                    }, 10000);
                }
                mStrategy.handleAccessbilityEvent(accessibilityEvent, mService);
                try {
                    if (mService.getRootInActiveWindow() != null) {
                        mService.getRootInActiveWindow().recycle();
                        return;
                    }
                } catch (IllegalStateException e) {

                } catch (Exception e2) {

                }
            }
        }
    };
    private List<String> mPermissionList;
    private boolean mPermissionOverview;
    private AccessibilityService mService;
    private boolean mStartupAutoChecking = false;
    private int mStep = 0;
    private IPermissionGuideStrategy mStrategy;
    private CompositeSubscription mSubscriptions = new CompositeSubscription();
    private List<ProgressState> stateList = new ArrayList();

    private PermissionStepFloatView floatView;


    private void onServiceInterrupt() {
        this.mService = null;
    }

    private void registerPermissionServiceListenerEvents() {
        Subscription subscribe = RxBus.getIns().toObservable(AccessibilityService.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<AccessibilityService>() {
            public void call(AccessibilityService accessibilityService) {
                onServiceConnected(accessibilityService);
            }
        });
        Subscription subscribe2 = RxBus.getIns().toObservable(ServiceInterruptEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<ServiceInterruptEvent>() {
            public void call(ServiceInterruptEvent serviceInterruptEvent) {
                onServiceInterrupt();
            }
        });
        this.mSubscriptions.add(subscribe);
        this.mSubscriptions.add(subscribe2);
    }

    private void registerPermissionFinishEvents() {
        this.mSubscriptions.add(RxBus.getIns().toObservable(FinishEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<FinishEvent>() {
            public void onCompleted() {
            }

            public void onError(Throwable th) {
            }

            public void onNext(FinishEvent finishEvent) {
                onFinishEvent(finishEvent);
            }
        }));
    }

    private void onFinishEvent(FinishEvent finishEvent) {
        if (finishEvent.getType().equals(GuideConst.TOAST_PERMISSION)) {
            if (floatView == null) {
                floatView = new PermissionStepFloatView(PermissionStepActivity.this, getPermissionList());
                floatView.updateProgress(0, false);
                floatView.show();
            }
        }
        for (int i = 0; i < this.stateList.size(); i++) {
            if (finishEvent.getType().equals((stateList.get(i)).type)) {
                if ((stateList.get(i)).state != 1) {
                    (stateList.get(i)).state = 1;
                    updateStepDone(i);
                    if (floatView != null)
                        floatView.updateStepDone(i);
                    break;
                } else {
                    return;
                }
            }
        }
        mPermissionEnterOnce = false;
        mUpdateFlag = true;
        int progressStatePercent = ProgressUtil.getProgressStatePercent(this.stateList);
        if (progressStatePercent >= 0 && progressStatePercent < 100) {
            updateProgress(progressStatePercent);
            if (floatView != null)
                floatView.updateProgress(progressStatePercent, false);
        } else {
            updateSuccess();
            if (floatView != null)
                floatView.updateProgress(progressStatePercent, true);
        }
    }

    @Override
    public void onBackPressed() {
        if (this.mService == null) {
            setResult(RESULT_CANCELED);
            closeActivity();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        dismissFloatWindow();
        if (this.mService == null) {
            startOptimize();
        } else {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    startOptimize();
                }
            });
        }
    }

    @Override
    public void onWindowFocusChanged(boolean z) {
        super.onWindowFocusChanged(z);
        if (z && this.mCommonView != null) {
            this.mCommonView.getLocationOnScreen(this.mCommonViewLoc);
        }
    }

    private void closeActivity() {
        this.mService = null;
        this.mStrategy = null;
        finish();
    }

    private void startOptimize() {
        if (this.mPermissionList != null && this.mService != null && this.mPermissionList.size() > 0) {
            if (this.mStrategy.allPermissionEnable(this.mPermissionList)) {

            } else if (canExitProcess()) {
                closeActivity();
            } else {
                if (this.mStartupAutoChecking) {
                    if (this.mStep >= 3) {
                        this.mHandler.postDelayed(new Runnable() {
                            public void run() {
                                executePermissionAction();
                            }
                        }, 500);
                    } else if (this.mPermissionOverview) {
                        this.mHandler.postDelayed(new Runnable() {
                            public void run() {
                                executePermissionAction();
                            }
                        }, 200);
                    } else {
                        this.mHandler.postDelayed(new Runnable() {
                            public void run() {
                                executePermissionAction();
                            }
                        }, 500);
                    }
                } else if (this.mPermissionOverview) {
                    this.mHandler.postDelayed(new Runnable() {
                        public void run() {
                            executePermissionAction();
                        }
                    }, 200);
                } else {
                    this.mHandler.postDelayed(new Runnable() {
                        public void run() {
                            executePermissionAction();
                        }
                    }, 2000);
                }
                if (canExitProcess()) {
                    closeActivity();
                }
            }
        } else if (this.mService == null && this.mStartupAutoChecking) {
            closeActivity();
        } else if (this.mService == null && this.mFirstLoad) {
            this.mFirstLoad = false;
        } else if (this.mService != null || this.mFirstLoad) {
            closeActivity();
        } else {
            //closeActivity();
        }
    }

    private boolean canExitProcess() {
        int size = this.mPermissionList.size();
        for (int i = 0; i < size; i++) {
            String str = (String) this.mPermissionList.get(i);
            if ((this.mExecuteMap.get(str) != null ? ((Integer) this.mExecuteMap.get(str)).intValue() : 0) < this.KMaxRetryCount && !this.mStrategy.getPermissionDone(str)) {
                return false;
            }
        }
        return true;
    }

    private void executePermissionAction()
    {
        if (this.mStrategy == null) {
            return;
        }
        this.mStartupAutoChecking = true;
        this.mStep += 1;
        int k = this.mPermissionList.size();
        while (mCurrentPermissionPos < k)
        {
            mLastPermissionPos = mCurrentPermissionPos;
            String str = (String)this.mPermissionList.get(mCurrentPermissionPos);
            boolean bool = this.mStrategy.getPermissionDone(str);
            if (!bool)
            {
                int j;
                if (this.mExecuteMap.get(str) != null) {
                    j = ((Integer)this.mExecuteMap.get(str)).intValue();
                } else {
                    j = 0;
                }

                if (j < this.KMaxRetryCount)
                {
                    this.mExecuteMap.put(str, Integer.valueOf(j + 1));
                    this.mStrategy.generateButtonFunction(str);
                    mCurrentPermissionPos++;
                    return;
                }
            }
            mCurrentPermissionPos += 1;
        }

        if (floatView != null)
            floatView.remove();

        checkResult();
    }

    private void dismissFloatWindow() {
        //sendBroadcast(new Intent("com.cootek.cn.ACTION_CLOSE_PERMISSION_GUIDE_FLOAT_WINDOW"));
    }

    protected void onDestroy() {
        super.onDestroy();
        this.mListener = null;
        this.mSubscriptions.unsubscribe();
    }

    public boolean onKeyDown(int i, KeyEvent keyEvent) {
        if (3 == i) {
            closeActivity();
            if (this.mIsOpenPopupWindow) {
            }
            //sendBroadcast(new Intent("com.cootek.cn.ACTION_CLOSE_PERMISSION_GUIDE_FLOAT_WINDOW"));
        }
        return super.onKeyDown(i, keyEvent);
    }

    public void setupStateList(List<String> list) {
        for (String str2 : list) {
            ProgressState progressState = new ProgressState();
            progressState.state = 0;
            progressState.type = str2;
            this.stateList.add(progressState);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acc_layout_step_detail);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        initData();
        initView();
    }

    private void initView() {
        findViewById(R.id.acc_step_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLastStepVideoDialog();
            }
        });
        mSetButton = findViewById(R.id.acc_step_set_action);
        mSetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PermissionWrapper.getInst().reportEvent("ClickAccessibility");
                startActivity(new Intent("android.settings.ACCESSIBILITY_SETTINGS"));
                if (mHandler != null) {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showPermissionGuide();
                        }
                    },100);
                }
            }
        });
        mTitle = findViewById(R.id.acc_step_title);

        if (mPermissionList != null) {
            mRecyclerView = findViewById(R.id.acc_step_recycler);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            mPermissionStepAdapter = new PermissionStepAdapter(this, getPermissionList());
            mRecyclerView.setAdapter(mPermissionStepAdapter);
        }
    }

    private void initData() {
        CallerShowUtils.setIsCanAuto(PackageUtil.queryAutoPermission());
        this.mStrategy = PermissionGuideGenerator.generateGuideStratagy(this, true);
        this.mPermissionList = this.mStrategy.getPermissionList();
        CallerShowUtils.checkAllPermissonToShow(this, this.mPermissionList);
        if (this.stateList == null || this.stateList.size() == 0) {
            setupStateList(this.mPermissionList);
        }
        registerPermissionFinishEvents();
        registerPermissionServiceListenerEvents();
        this.mPermissionOverview = PackageUtil.isPermissionGuideOverview();
        if (this.mService == null) {
            if (this.mStrategy != null) {
                this.mStrategy.configAccessbility(this.mService);
            }
        }
        PermissionRouteHandler.getInstance().setRealStartPermission(true);
    }

    public void updateProgress(int progress) {
        mSetButton.setText(getString(R.string.acc_step_detail_set_action_fixing, progress));
        mSetButton.setBackgroundResource(R.drawable.acc_layout_step_detail_btn_fixing_bg);
        mSetButton.setEnabled(false);
        mTitle.setText(Html.fromHtml(getString(R.string.acc_step_detail_title_fixing, progress)));
    }

    public void updateSuccess() {
        PermissionWrapper.getInst().reportEvent("AccessibilitySuccess");
        mSetButton.setText(getString(R.string.acc_step_detail_set_action_success));
        mSetButton.setBackgroundResource(R.drawable.acc_layout_step_detail_btn_fixing_bg);
        mSetButton.setEnabled(false);
        mTitle.setText(getString(R.string.acc_step_detail_title_success));
        findViewById(R.id.acc_step_back).setEnabled(false);
        if (mHandler != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setResult(RESULT_SUCCESS);
                    closeActivity();
                }
            },2000);
        }
    }

    public void updateUnfinished() {
        mSetButton.setText(getString(R.string.acc_step_detail_set_action_manual));
        mSetButton.setBackgroundResource(R.drawable.acc_layout_step_detail_btn_bg);
        mSetButton.setEnabled(true);
        mSetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_FAILED);
                closeActivity();
            }
        });
        mTitle.setText(getString(R.string.acc_step_detail_title_failed));
        findViewById(R.id.acc_step_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_FAILED);
                closeActivity();
            }
        });
    }

    public void updateStepDone(int index) {
        mPermissionStepAdapter.setStatusDone(index);
        mPermissionStepAdapter.notifyItemChanged(index, PermissionStepAdapter.UPDATE_STATUS);
    }

    private void showLastStepVideoDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.acc_step_exit_warn_dialog, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);

        if (mExitDialog == null)
            mExitDialog = builder.create();

        try {
            mExitDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        } catch (Exception e) {}

        mExitDialog.setCanceledOnTouchOutside(false);
        mExitDialog.setCancelable(false);

        view.findViewById(R.id.exit_goon_action_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isFinishing() && mExitDialog != null)
                    mExitDialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isFinishing() && mExitDialog != null)
                    mExitDialog.dismiss();
            }
        });

        view.findViewById(R.id.exit_force_action_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        if(!isFinishing() && mExitDialog != null && !mExitDialog.isShowing())
            mExitDialog.show();
    }

    private void onServiceConnected(AccessibilityService accessibilityService) {
        String str = TAG;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("onServiceConnected ");
        stringBuilder.append(accessibilityService);
        this.mService = accessibilityService;
        PermissionAccessibilityService.setListener(this.mListener);
        dismissFloatWindow();
        str = TAG;
        stringBuilder = new StringBuilder();
        stringBuilder.append("Service = ");
        stringBuilder.append(this.mService);
        stringBuilder.append("\nStrategy = ");
        stringBuilder.append(this.mStrategy);
        if (this.mStrategy == null) {
            try {
                this.mStrategy = PermissionGuideGenerator.generateGuideStratagy(this, true);
            } catch (Exception unused) {

            }
        }

        if (this.mStrategy != null) {
            this.mStrategy.configAccessbility(accessibilityService);
        }
    }

    private void showPermissionGuide() {
        Intent intentGuide = new Intent(com.kk.permission.PermissionStepActivity.this, AccPermissionGuideActivity.class);
        startActivity(intentGuide);
        overridePendingTransition(0, 0);
    }

    // 需要请求的当前权限列表
    private ArrayList<String> getPermissionList(){
        return CallerShowUtils.getPermissionListName(this, mPermissionList);
    }

    // 当前permission position
    private int getCurrentPermissionPos(){
        return mCurrentPermissionPos;
    }

    private void checkResult() {
        if (PermissionWrapper.getInst().isDefaultDialer() || PermissionWrapper.getInst().isNotifiAccessEnabled()) {
            updateSuccess();
        } else {
            updateUnfinished();
        }
    }
}
